package com.jcli.jb51_net.article._175980开关按钮;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @ClassName JMain
 * @Description TODO
 * @Author li
 * @Data 2023/12/15 10:10
 * @Version 1.0
 */
public class JMain {
    public static void main(String[] args) {
        JFrame jf = new JFrame("测试窗口");
        jf.setSize(500, 500);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        String imp = "pic/Firefly 名字JCli，软件图标，机械风 67840.jpg";
        ImageIcon img = new ImageIcon(imp);
        jf.setIconImage(img.getImage());

        JPanel panel = new JPanel();
        // panel.setBackground(new Color(238,238,238));

        //    创建开关按钮
        JToggleButton tb = new JToggleButton();

        //    不绘制按钮边框
        // tb.setBorderPainted(false);

        tb.setRolloverEnabled(false); // 禁用鼠标悬停效果
        tb.setBorderPainted(false); // 禁用边框绘制
        tb.setContentAreaFilled(false); // 禁用内容区域填充

        //    设置选中开，未选择关的照片
        tb.setSelectedIcon(new ImageIcon("./pic/Snipaste_2023-12-25_12-02-52.png"));
        tb.setIcon(new ImageIcon("./pic/Snipaste_2023-12-25_12-03-24.png"));
        // tb.setBackground(new Color(238,238,238));

        //    添加按钮被改变的监听
        tb.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                //    获取事件源
                JToggleButton tb = (JToggleButton) e.getSource();
                // tb.setBackground(new Color(238,238,238));
                System.out.println(tb.getText() + "是否选中" + tb.isSelected());

            }
        });

        tb.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!JTBUtils.isFastClick(tb)) {
                    if (tb.isSelected()) {
                        System.out.println("Toggle button selected!");
                        // 在这里放置选中时的逻辑
                    } else {
                        System.out.println("Toggle button deselected!");
                        // 在这里放置取消选中时的逻辑
                    }
                } else {
                    System.out.println("Too fast! Ignoring toggle.");
                    // 在这里放置点击太快时的逻辑
                }
            }
        });

        panel.add(tb);

        jf.setContentPane(panel);
        jf.setVisible(true);
    }
}
